package com.ksc.storekeeper.client.view.impl;

import com.github.gwtbootstrap.client.ui.Button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.ViewImpl;
import com.ksc.storekeeper.client.view.ChangePasswordView;
import com.ksc.storekeeper.client.view.components.FormItemPasswordBox;

public class ChangePasswordViewImpl extends ViewImpl implements ChangePasswordView {

	private final Widget widget;
	private final ChangePasswordViewUiBinder uiBinder = GWT.create(ChangePasswordViewUiBinder.class);
	private ChangePasswordUiHandler uiHandler;

	@UiField
	HTML infoMsg;

	@UiField
	Button changePassword;

	@UiField
	FormItemPasswordBox oldPassword;

	@UiField
	FormItemPasswordBox newPassword;

	@UiField
	FormItemPasswordBox confirmPassword;

	interface ChangePasswordViewUiBinder extends UiBinder<Widget, ChangePasswordViewImpl> {

	}

	public ChangePasswordViewImpl() {
		widget = uiBinder.createAndBindUi(this);
	}

	private boolean validate() {
		boolean valid = oldPassword.validate() & newPassword.validate() & confirmPassword.validate();
		return valid;
	}

	@UiHandler("changePassword")
	public void onChangePasswordClicked(final ClickEvent event) {
		if (validate()) {
			String old = oldPassword.getText();
			String newPass = newPassword.getText();
			String confirm = confirmPassword.getText();
			if (!newPass.equals(confirm)) {
				infoMsg.setText("Password don't match");
			} else {
				uiHandler.changePassword(old, newPass);
			}
		}
	}

	@Override
	public Widget asWidget() {
		return this.widget;
	}

	@Override
	public void setUiHandlers(ChangePasswordUiHandler uiHandlers) {
		this.uiHandler = uiHandlers;
	}

}
